<template>
  <div class="fuel-records-management">
    <!-- 筛选和搜索栏 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-group">
          <label for="vehicle-filter">车辆</label>
          <select
            id="vehicle-filter"
            v-model="filters.vehicle_id"
            @change="fetchRecords"
          >
            <option value="">全部车辆</option>
            <option
              v-for="vehicle in vehicles"
              :key="vehicle.id"
              :value="vehicle.id"
            >
              {{ vehicle.name }}
            </option>
          </select>
        </div>

        <div class="filter-group">
          <label for="station-filter">加油站类型</label>
          <select
            id="station-filter"
            v-model="filters.gas_station_type"
            @change="fetchRecords"
          >
            <option value="">全部类型</option>
            <option v-for="type in gasStationTypes" :key="type" :value="type">
              {{ type }}
            </option>
          </select>
        </div>

        <div class="filter-group">
          <label for="start-date">开始日期</label>
          <input
            id="start-date"
            v-model="filters.start_date"
            type="date"
            @change="fetchRecords"
          />
        </div>

        <div class="filter-group">
          <label for="end-date">结束日期</label>
          <input
            id="end-date"
            v-model="filters.end_date"
            type="date"
            @change="fetchRecords"
          />
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card>
        <div class="stat-card">
          <div class="stat-icon">⛽</div>
          <div class="stat-content">
            <div class="stat-label">总加油量</div>
            <div class="stat-value">{{ totalFuelAmount.toFixed(2) }} 升</div>
          </div>
        </div>
      </el-card>

      <el-card>
        <div class="stat-card">
          <div class="stat-icon">💰</div>
          <div class="stat-content">
            <div class="stat-label">总费用</div>
            <div class="stat-value">¥{{ totalFuelCost.toFixed(2) }}</div>
          </div>
        </div>
      </el-card>

      <el-card>
        <div class="stat-card">
          <div class="stat-icon">📊</div>
          <div class="stat-content">
            <div class="stat-label">平均油耗</div>
            <div class="stat-value">
              {{ avgFuelConsumption.toFixed(2) }} L/100km
            </div>
          </div>
        </div>
      </el-card>

      <el-card>
        <div class="stat-card">
          <div class="stat-icon">🚗</div>
          <div class="stat-content">
            <div class="stat-label">记录数量</div>
            <div class="stat-value">{{ fuelRecords.length }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 详细统计信息 -->
    <el-collapse v-model="activeCollapse">
      <el-collapse-item name="detailed-stats">
        <template #title>
          <div class="collapse-header">
            <el-icon><DataLine /></el-icon>
            <span>详细油耗统计</span>
          </div>
        </template>
        
        <!-- 详细统计筛选器 -->
        <div class="detailed-stats-filters">
          <el-form :model="detailedFilters" inline>
            <el-form-item label="车辆">
              <el-select v-model="detailedFilters.vehicle_id" placeholder="全部车辆" clearable @change="fetchDetailedStats">
                <el-option
                  v-for="vehicle in vehicles"
                  :key="vehicle.id"
                  :label="vehicle.name"
                  :value="vehicle.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="detailedFilters.start_date"
                type="date"
                placeholder="选择开始日期"
                clearable
                @change="fetchDetailedStats"
              />
            </el-form-item>
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="detailedFilters.end_date"
                type="date"
                placeholder="选择结束日期"
                clearable
                @change="fetchDetailedStats"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchDetailedStats" :loading="detailedStatsLoading">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 详细统计内容 -->
        <div v-if="detailedStats" class="detailed-stats-content">
          <!-- 主要统计指标 -->
          <el-row :gutter="16">
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <div class="stat-icon">📊</div>
                  <div class="stat-content">
                    <div class="stat-label">平均油耗</div>
                    <div class="stat-value">{{ detailedStats.avg_fuel_consumption?.toFixed(2) || '0.00' }} L/100km</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <div class="stat-icon">💰</div>
                  <div class="stat-content">
                    <div class="stat-label">总费用</div>
                    <div class="stat-value">¥{{ detailedStats.total_fuel_cost?.toFixed(2) || '0.00' }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <div class="stat-icon">⛽</div>
                  <div class="stat-content">
                    <div class="stat-label">总加油量</div>
                    <div class="stat-value">{{ detailedStats.total_fuel_amount?.toFixed(2) || '0.00' }} 升</div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <div class="stat-item">
                  <div class="stat-icon">🛣️</div>
                  <div class="stat-content">
                    <div class="stat-label">总里程</div>
                    <div class="stat-value">{{ detailedStats.total_distance?.toFixed(0) || '0' }} km</div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 费用汇总 -->
          <el-card class="cost-summary-card">
            <template #header>
              <div class="card-header">
                <span>费用汇总</span>
              </div>
            </template>
            <el-row :gutter="16">
              <el-col :span="8">
                <div class="cost-item">
                  <span class="cost-label">总费用:</span>
                  <span class="cost-value">¥{{ costSummary?.total_cost?.toFixed(2) || '0.00' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="cost-item">
                  <span class="cost-label">月均费用:</span>
                  <span class="cost-value">¥{{ costSummary?.monthly_average?.toFixed(2) || '0.00' }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="cost-item">
                  <span class="cost-label">日均费用:</span>
                  <span class="cost-value">¥{{ costSummary?.daily_average?.toFixed(2) || '0.00' }}</span>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <!-- 车辆对比 -->
          <el-card v-if="vehiclesWithStats.length > 0">
            <template #header>
              <div class="card-header">
                <span>车辆对比</span>
              </div>
            </template>
            <el-row :gutter="16">
              <el-col 
                v-for="vehicleWithStats in vehiclesWithStats" 
                :key="vehicleWithStats.vehicle.id" 
                :span="12"
              >
                <el-card class="vehicle-comparison-card">
                  <div class="vehicle-header">
                    <h4>{{ vehicleWithStats.vehicle.name }}</h4>
                    <el-tag :type="vehicleWithStats.vehicle.is_active ? 'success' : 'warning'">
                      {{ vehicleWithStats.vehicle.is_active ? '使用中' : '已停用' }}
                    </el-tag>
                  </div>
                  <div class="vehicle-stats">
                    <div class="vehicle-stat-item">
                      <span class="stat-label">油耗:</span>
                      <span class="stat-value">
                        {{ vehicleWithStats.fuel_stats?.avg_fuel_consumption?.toFixed(2) || 'N/A' }} L/100km
                      </span>
                    </div>
                    <div class="vehicle-stat-item">
                      <span class="stat-label">总费用:</span>
                      <span class="stat-value">
                        ¥{{ vehicleWithStats.fuel_stats?.total_fuel_cost?.toFixed(2) || '0.00' }}
                      </span>
                    </div>
                    <div class="vehicle-stat-item">
                      <span class="stat-label">记录数:</span>
                      <span class="stat-value">
                        {{ vehicleWithStats.fuel_stats?.record_count || 0 }}
                      </span>
                    </div>
                  </div>
                  <div v-if="vehicleWithStats.latest_fuel_record" class="latest-record">
                    <div class="latest-record-header">
                      <span class="latest-label">最新记录</span>
                      <span class="latest-date">{{ formatDate(vehicleWithStats.latest_fuel_record.refuel_date) }}</span>
                    </div>
                    <div class="latest-record-details">
                      <span>{{ vehicleWithStats.latest_fuel_record.fuel_amount.toFixed(2) }}升</span>
                      <span>¥{{ vehicleWithStats.latest_fuel_record.fuel_cost.toFixed(2) }}</span>
                      <span>{{ vehicleWithStats.latest_fuel_record.current_mileage.toFixed(0) }}km</span>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-card>

          <!-- 趋势图表 -->
          <el-card v-if="detailedStats && detailedStats.record_count > 0">
            <template #header>
              <div class="card-header">
                <span>油耗趋势</span>
              </div>
            </template>
            <div class="trend-chart">
              <div class="chart-placeholder">
                <el-empty description="图表功能开发中..." />
              </div>
            </div>
          </el-card>
        </div>

        <!-- 加载状态 -->
        <div v-else-if="detailedStatsLoading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-container">
          <el-empty description="暂无详细统计数据" />
        </div>
      </el-collapse-item>
    </el-collapse>

    <!-- 加油记录列表 -->
    <div class="records-section">
      <div class="section-header">
        <h3>加油记录</h3>
        <button @click="showAddModal = true" class="add-button">
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
          >
            <line x1="12" y1="5" x2="12" y2="19"></line>
            <line x1="5" y1="12" x2="19" y2="12"></line>
          </svg>
          添加记录
        </button>
      </div>

      <div v-if="loading && fuelRecords.length === 0" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>

      <div v-else-if="fuelRecords.length === 0" class="empty-state">
        <svg
          width="64"
          height="64"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1"
        >
          <path
            d="M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z"
          />
          <path d="M12 8v4M12 16h.01" />
        </svg>
        <p>暂无加油记录</p>
        <button @click="showAddModal = true" class="add-button">
          添加第一条记录
        </button>
      </div>

      <div v-else class="records-list">
        <div v-for="record in fuelRecords" :key="record.id" class="record-card">
          <div class="record-header">
            <div class="record-vehicle">
              <span class="vehicle-name">{{ record.vehicle_name }}</span>
              <span class="record-date">{{
                formatDate(record.refuel_date)
              }}</span>
            </div>
            <div class="record-actions">
              <button @click="editRecord(record)" class="action-button edit">
                <svg
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <path
                    d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"
                  />
                  <path
                    d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"
                  />
                </svg>
              </button>
              <button
                @click="deleteRecord(record)"
                class="action-button delete"
              >
                <svg
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <path
                    d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6h14zM10 11v6M14 11v6"
                  />
                </svg>
              </button>
            </div>
          </div>

          <div class="record-details">
            <div class="detail-grid">
              <div class="detail-item">
                <span class="detail-label">加油量</span>
                <span class="detail-value"
                  >{{ record.fuel_amount.toFixed(2) }} 升</span
                >
              </div>
              <div class="detail-item">
                <span class="detail-label">金额</span>
                <span class="detail-value"
                  >¥{{ record.fuel_cost.toFixed(2) }}</span
                >
              </div>
              <div class="detail-item">
                <span class="detail-label">油价</span>
                <span class="detail-value"
                  >¥{{ record.fuel_price.toFixed(2) }}/升</span
                >
              </div>
              <div class="detail-item">
                <span class="detail-label">里程</span>
                <span class="detail-value"
                  >{{ record.current_mileage.toFixed(0) }} km</span
                >
              </div>
              <div class="detail-item">
                <span class="detail-label">加油站</span>
                <span class="detail-value">{{ record.gas_station_type }}</span>
              </div>
              <div v-if="record.fuel_consumption" class="detail-item">
                <span class="detail-label">油耗</span>
                <span class="detail-value"
                  >{{ record.fuel_consumption.toFixed(2) }} L/100km</span
                >
              </div>
            </div>
            <div v-if="record.notes" class="record-notes">
              <span class="detail-label">备注:</span>
              <span class="detail-value">{{ record.notes }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑记录模态框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="showAddModal ? '添加加油记录' : '编辑加油记录'"
      width="600px"
      :close-on-click-modal="false"
      @close="closeModals"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="车辆" prop="vehicle_id">
          <el-select
            v-model="formData.vehicle_id"
            placeholder="请选择车辆"
            style="width: 100%"
          >
            <el-option
              v-for="vehicle in vehicles"
              :key="vehicle.id"
              :label="vehicle.name"
              :value="vehicle.id"
            />
          </el-select>
        </el-form-item>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="当前里程 (km)" prop="current_mileage">
              <el-input-number
                v-model="formData.current_mileage"
                :precision="1"
                :min="0"
                :step="0.1"
                placeholder="例如：15000.5"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加油量 (升)" prop="fuel_amount">
              <el-input-number
                v-model="formData.fuel_amount"
                :precision="2"
                :min="0"
                :step="0.01"
                placeholder="例如：40.5"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="加油金额 (元)" prop="fuel_cost">
              <el-input-number
                v-model="formData.fuel_cost"
                :precision="2"
                :min="0"
                :step="0.01"
                placeholder="例如：300.5"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="油价 (元/升)" prop="fuel_price">
              <el-input-number
                v-model="formData.fuel_price"
                :precision="2"
                :min="0"
                :step="0.01"
                placeholder="例如：7.5"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="加油站类型" prop="gas_station_type">
              <el-select
                v-model="formData.gas_station_type"
                placeholder="请选择加油站类型"
                style="width: 100%"
              >
                <el-option
                  v-for="type in gasStationTypes"
                  :key="type"
                  :label="type"
                  :value="type"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加油日期" prop="refuel_date">
              <el-date-picker
                v-model="formData.refuel_date"
                type="datetime"
                placeholder="选择加油日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input
            v-model="formData.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeModals">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
          >
            {{ loading ? "保存中..." : showAddModal ? "添加" : "保存" }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="showDeleteModal"
      title="确认删除"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="delete-content">
        <el-alert
          title="确定要删除这条加油记录吗？"
          type="warning"
          :closable="false"
          show-icon
        >
          <p>此操作不可撤销。</p>
        </el-alert>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDeleteModal = false">取消</el-button>
          <el-button
            type="danger"
            @click="confirmDelete"
            :loading="loading"
          >
            {{ loading ? "删除中..." : "确认删除" }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useVehicleStore } from "@/stores/vehicle";
import { DataLine, Refresh } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import type {
  VehicleFuelRecordResponse,
  VehicleFuelRecordCreate,
  VehicleFuelRecordUpdate,
  VehicleResponse,
  VehicleFuelRecordListParams,
  VehicleWithFuelStats,
  FuelConsumptionStats,
  FuelConsumptionStatsParams,
} from "@/types/vehicle";

// 车辆store
const vehicleStore = useVehicleStore();

// 表单引用
const formRef = ref<FormInstance>();

// 响应式状态
const vehicles = ref<VehicleResponse[]>([]);
const fuelRecords = ref<VehicleFuelRecordResponse[]>([]);
const gasStationTypes = ref<string[]>([]);
const loading = ref(false);
const showAddModal = ref(false);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const recordToDelete = ref<VehicleFuelRecordResponse | null>(null);
const currentEditingId = ref<number | null>(null);

// 详细统计相关状态
const activeCollapse = ref<string[]>([]);
const detailedStats = ref<FuelConsumptionStats | null>(null);
const vehiclesWithStats = ref<VehicleWithFuelStats[]>([]);
const costSummary = ref<{
  total_cost?: number;
  monthly_average?: number;
  daily_average?: number;
} | null>(null);
const detailedStatsLoading = ref(false);

// 详细统计筛选器
const detailedFilters = reactive<FuelConsumptionStatsParams>({
  vehicle_id: undefined,
  start_date: undefined,
  end_date: undefined,
});

// 筛选条件
const filters = reactive<VehicleFuelRecordListParams>({
  vehicle_id: undefined,
  gas_station_type: undefined,
  start_date: undefined,
  end_date: undefined,
});

// 表单数据
const formData = reactive<
  Partial<VehicleFuelRecordCreate & VehicleFuelRecordUpdate>
>({
  vehicle_id: undefined,
  current_mileage: undefined,
  fuel_amount: undefined,
  fuel_cost: undefined,
  fuel_price: undefined,
  gas_station_type: undefined,
  refuel_date: undefined,
  notes: undefined,
});

// 表单验证规则
const formRules: FormRules = {
  vehicle_id: [
    { required: true, message: '请选择车辆', trigger: 'change' }
  ],
  current_mileage: [
    { required: true, message: '请输入当前里程', trigger: 'blur' },
    { type: 'number', min: 0, message: '里程必须大于0', trigger: 'blur' }
  ],
  fuel_amount: [
    { required: true, message: '请输入加油量', trigger: 'blur' },
    { type: 'number', min: 0, message: '加油量必须大于0', trigger: 'blur' }
  ],
  fuel_cost: [
    { required: true, message: '请输入加油金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '加油金额必须大于0', trigger: 'blur' }
  ],
  fuel_price: [
    { required: true, message: '请输入油价', trigger: 'blur' },
    { type: 'number', min: 0, message: '油价必须大于0', trigger: 'blur' }
  ],
  gas_station_type: [
    { required: true, message: '请选择加油站类型', trigger: 'change' }
  ],
  refuel_date: [
    { required: true, message: '请选择加油日期', trigger: 'change' }
  ]
};

// 计算属性
const dialogVisible = computed({
  get: () => showAddModal.value || showEditModal.value,
  set: (value) => {
    if (!value) {
      closeModals();
    }
  }
});

const totalFuelAmount = computed(() =>
  fuelRecords.value.reduce((sum, record) => sum + record.fuel_amount, 0),
);

const totalFuelCost = computed(() =>
  fuelRecords.value.reduce((sum, record) => sum + record.fuel_cost, 0),
);

const avgFuelConsumption = computed(() => {
  const validRecords = fuelRecords.value.filter(
    (r) => r.fuel_consumption !== null && r.fuel_consumption !== undefined,
  );
  if (validRecords.length === 0) return 0;
  return (
    validRecords.reduce((sum, record) => sum + record.fuel_consumption!, 0) /
    validRecords.length
  );
});

// 清除表单
const clearForm = () => {
  currentEditingId.value = null;
  Object.assign(formData, {
    vehicle_id: undefined,
    current_mileage: undefined,
    fuel_amount: undefined,
    fuel_cost: undefined,
    fuel_price: undefined,
    gas_station_type: undefined,
    refuel_date: new Date(),
    notes: undefined,
  });
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};


// 获取车辆列表
const fetchVehicles = async () => {
  try {
    const response = await vehicleStore.fetchVehicles();
    vehicles.value = response.vehicles;
  } catch (error) {
    console.error("获取车辆列表失败:", error);
  }
};

// 获取加油站类型
const fetchGasStationTypes = async () => {
  try {
    gasStationTypes.value = await vehicleStore.fetchGasStationTypes();
  } catch (error) {
    console.error("获取加油站类型失败:", error);
  }
};

// 获取详细统计信息
const fetchDetailedStats = async () => {
  try {
    detailedStatsLoading.value = true;
    
    // 获取油耗统计
    detailedStats.value = await vehicleStore.fetchFuelStats(detailedFilters);
    
    // 获取费用汇总
    const costFilters = {
      start_date: detailedFilters.start_date || undefined,
      end_date: detailedFilters.end_date || undefined,
      vehicle_id: detailedFilters.vehicle_id || undefined,
    };
    costSummary.value = await vehicleStore.fetchFuelCostSummary(costFilters);
    
    // 获取车辆对比数据
    vehiclesWithStats.value = await vehicleStore.fetchVehiclesWithStats();
  } catch (error) {
    console.error("获取详细统计失败:", error);
  } finally {
    detailedStatsLoading.value = false;
  }
};

// 获取加油记录
const fetchRecords = async () => {
  try {
    loading.value = true;
    const response = await vehicleStore.fetchFuelRecords(filters);
    fuelRecords.value = response.fuel_records;
  } catch (error) {
    console.error("获取加油记录失败:", error);
  } finally {
    loading.value = false;
  }
};

// 编辑记录
const editRecord = (record: VehicleFuelRecordResponse) => {
  currentEditingId.value = record.id;
  Object.assign(formData, {
    vehicle_id: record.vehicle_id,
    current_mileage: record.current_mileage,
    fuel_amount: record.fuel_amount,
    fuel_cost: record.fuel_cost,
    fuel_price: record.fuel_price,
    gas_station_type: record.gas_station_type,
    refuel_date: new Date(record.refuel_date).toISOString().slice(0, 16),
    notes: record.notes,
  });
  showEditModal.value = true;
};

// 删除记录
const deleteRecord = (record: VehicleFuelRecordResponse) => {
  recordToDelete.value = record;
  showDeleteModal.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!recordToDelete.value) return;

  try {
    loading.value = true;
    await vehicleStore.deleteFuelRecord(recordToDelete.value.id);
    await fetchRecords();
    showDeleteModal.value = false;
    recordToDelete.value = null;
  } catch (error) {
    console.error("删除加油记录失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    // 表单验证
    await formRef.value.validate();
    
    loading.value = true;

    if (showAddModal.value) {
      // 创建记录
      await vehicleStore.createFuelRecord(formData as VehicleFuelRecordCreate);
    } else {
      // 更新记录
      await vehicleStore.updateFuelRecord(
        currentEditingId.value!,
        formData as VehicleFuelRecordUpdate,
      );
    }

    await fetchRecords();
    closeModals();
  } catch (error) {
    console.error("保存加油记录失败:", error);
  } finally {
    loading.value = false;
  }
};

// 关闭模态框
const closeModals = () => {
  showAddModal.value = false;
  showEditModal.value = false;
  clearForm();
};

// 格式化日期
const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleString("zh-CN");
};

// 监听筛选条件变化
watch([() => filters.vehicle_id, () => filters.gas_station_type], () => {
  fetchRecords();
});

// 监听折叠面板状态变化
watch(activeCollapse, (newVal) => {
  if (newVal.includes('detailed-stats') && !detailedStats.value) {
    fetchDetailedStats();
  }
});

// 组件挂载时获取数据
onMounted(async () => {
  await Promise.all([fetchVehicles(), fetchGasStationTypes(), fetchRecords()]);
});
</script>

<style scoped lang="scss">
@use "@/styles/mixins" as *;

.fuel-records-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.filter-section {
  margin-bottom: 24px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  font-size: 24px;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.records-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.add-button {
  display: flex;
  align-items: center;
  gap: 8px;
}

.loading-state {
  text-align: center;
  padding: 40px;
  color: var(--el-text-color-secondary);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--el-text-color-secondary);

  svg {
    margin-bottom: 16px;
    opacity: 0.5;
  }

  p {
    margin-bottom: 20px;
    font-size: 16px;
  }
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.record-card {
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.record-vehicle {
  flex: 1;
}

.vehicle-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.record-date {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.record-actions {
  display: flex;
  gap: 8px;
}

.action-button {
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.record-details {
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 16px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
  margin-bottom: 12px;
}

.detail-item {
  display: flex;
  flex-direction: column;
}

.detail-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 2px;
}

.detail-value {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.record-notes {
  display: flex;
  align-items: flex-start;
  gap: 8px;

  .detail-label {
    margin-bottom: 0;
    margin-top: 2px;
  }

  .detail-value {
    flex: 1;
    font-weight: normal;
  }
}

// 详细统计样式
.collapse-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detailed-stats-filters {
  margin-bottom: 24px;
}

.detailed-stats-content {
  .el-card {
    margin-bottom: 16px;
  }
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.cost-summary-card {
  .cost-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    
    .cost-label {
      font-weight: 500;
      color: var(--el-text-color-regular);
    }
    
    .cost-value {
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
}

.vehicle-comparison-card {
  margin-bottom: 16px;
}

.vehicle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.vehicle-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.vehicle-stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: var(--el-fill-color-light);
  border-radius: 4px;

  .stat-label {
    font-size: 14px;
    color: var(--el-text-color-regular);
  }

  .stat-value {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }
}

.latest-record {
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 16px;

  .latest-record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .latest-label {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }

    .latest-date {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }

  .latest-record-details {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      font-size: 13px;
      color: var(--el-text-color-primary);
      font-weight: 500;
    }
  }
}

.trend-chart {
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-container {
  padding: 20px;
}

.empty-container {
  padding: 40px 20px;
  text-align: center;
}
</style>
